// LoginPage.js
import axios from 'axios';
import React, { useState } from 'react';
import {  Link } from 'react-router-dom';
import '../style/LoginPage.css';

const LoginPage = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [emailError, setEmailError] = useState('');

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
    // 在用户输入后进行验证
    if (e.target.value !== '') {
      if (!validateEmail(e.target.value)) {
        setEmailError('请输入有效的邮箱地址');
      } else {
        setEmailError('');
      }
    } else {
      setEmailError('');
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateEmail(email)) {
      setEmailError('请输入有效的邮箱地址');
      return;
    }
    
    try {
      const response = await axios.post('/api/login', { email, password });
      if (response.data.success) {
        // 登录成功，可以执行一些操作，比如跳转到其他页面
        console.log(response.data.message);
      } else {
        // 登录失败，显示错误消息
        console.error(response.data.message);
      }
    } catch (error) {
      // 处理请求失败的情况
      console.error('请求错误:', error);
    }
  
    // 清空表单字段
    setEmail('');
    setPassword('');
    setEmailError('');
  };

  const validateEmail = (email) => {
    const re = /\S+@\S+\.\S+/;
    return re.test(email);
  };

  return (
    <div className="login-container">
      <h2>登录</h2>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="email">邮箱：</label>
          <input
            type="email"
            id="email"
            value={email}
            onChange={handleEmailChange}
            required
          />
          {emailError && <p className="error-msg">{emailError}</p>}
        </div>
        <div className="form-group">
          <label htmlFor="password">密码：</label>
          <input
            type="password"
            id="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </div>
        <button type="submit">登录</button>
        <p>没有账号？<Link to="/register">立即注册</Link></p>
      </form>
    </div>
  );
};

export default LoginPage;
